#!/usr/bin/env python3
"""
AIQuant异步问题诊断脚本
专门诊断事件循环冲突和DataCache问题
"""

import asyncio
import sys
import traceback
from pathlib import Path

# 添加项目路径
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

def test_datacache_cleanup():
    """测试1: 检查DataCache是否有cleanup方法"""
    print("🔍 测试1: 检查DataCache cleanup方法")
    try:
        from aiquant.data.data_manager import DataManager
        from aiquant.data.cache import DataCache
        
        # 检查DataCache类
        cache = DataCache()
        print(f"✅ DataCache实例创建成功")
        
        # 检查cleanup方法
        if hasattr(cache, 'cleanup'):
            print(f"✅ DataCache.cleanup方法存在")
        else:
            print(f"❌ DataCache.cleanup方法不存在")
            print(f"📋 DataCache可用方法: {[m for m in dir(cache) if not m.startswith('_')]}")
            
        # 检查close方法
        if hasattr(cache, 'close'):
            print(f"✅ DataCache.close方法存在")
        else:
            print(f"❌ DataCache.close方法不存在")
            
        return True
        
    except Exception as e:
        print(f"❌ DataCache检查失败: {e}")
        traceback.print_exc()
        return False

def test_get_async_engine_import():
    """测试2: 检查get_async_engine导入问题"""
    print("\n🔍 测试2: 检查get_async_engine导入")
    try:
        from aiquant.config.database import get_async_engine
        print(f"✅ get_async_engine导入成功")
        return True
    except ImportError as e:
        print(f"❌ get_async_engine导入失败: {e}")
        
        # 检查database模块中实际存在的函数
        try:
            import aiquant.config.database as db_module
            functions = [name for name in dir(db_module) if not name.startswith('_') and callable(getattr(db_module, name))]
            print(f"📋 database模块可用函数: {functions}")
        except Exception as e2:
            print(f"❌ 无法检查database模块: {e2}")
        
        return False
    except Exception as e:
        print(f"❌ get_async_engine检查失败: {e}")
        return False

async def test_event_loop_isolation():
    """测试3: 测试事件循环隔离"""
    print("\n🔍 测试3: 测试事件循环隔离")
    try:
        current_loop = asyncio.get_running_loop()
        print(f"✅ 当前事件循环: {current_loop}")
        
        # 测试数据库连接在当前循环中的行为
        from aiquant.config.database import DatabaseConfig
        db_config = DatabaseConfig()
        print(f"✅ DatabaseConfig创建成功")
        
        # 检查引擎是否在同一循环中
        if hasattr(db_config, 'engine') and db_config.engine:
            print(f"✅ 数据库引擎已存在")
        else:
            print(f"ℹ️ 数据库引擎未初始化")
            
        return True
        
    except Exception as e:
        print(f"❌ 事件循环测试失败: {e}")
        traceback.print_exc()
        return False

async def test_simple_lifespan():
    """测试4: 简化的lifespan测试（不使用TestClient）"""
    print("\n🔍 测试4: 简化lifespan测试")
    try:
        from aiquant.main import create_app
        
        # 创建应用但不启动TestClient
        app = create_app()
        print(f"✅ FastAPI应用创建成功")
        
        # 手动测试lifespan逻辑
        from aiquant.main import lifespan
        
        # 模拟启动
        print("🔄 模拟启动过程...")
        async with lifespan(app):
            print("✅ lifespan启动成功")
            await asyncio.sleep(0.1)  # 模拟运行时间
            print("✅ lifespan运行正常")
        
        print("✅ lifespan关闭成功")
        return True
        
    except Exception as e:
        print(f"❌ 简化lifespan测试失败: {e}")
        traceback.print_exc()
        return False

def test_database_module_structure():
    """测试5: 检查数据库模块结构"""
    print("\n🔍 测试5: 检查数据库模块结构")
    try:
        import aiquant.config.database as db_module
        
        # 列出所有属性和方法
        all_items = dir(db_module)
        classes = [name for name in all_items if not name.startswith('_') and isinstance(getattr(db_module, name, None), type)]
        functions = [name for name in all_items if not name.startswith('_') and callable(getattr(db_module, name, None)) and not isinstance(getattr(db_module, name, None), type)]
        variables = [name for name in all_items if not name.startswith('_') and not callable(getattr(db_module, name, None)) and not isinstance(getattr(db_module, name, None), type)]
        
        print(f"📋 数据库模块类: {classes}")
        print(f"📋 数据库模块函数: {functions}")
        print(f"📋 数据库模块变量: {variables}")
        
        # 特别检查是否有类似get_async_engine的函数
        engine_related = [name for name in functions if 'engine' in name.lower()]
        print(f"📋 引擎相关函数: {engine_related}")
        
        return True
        
    except Exception as e:
        print(f"❌ 数据库模块结构检查失败: {e}")
        return False

async def main():
    """主诊断函数"""
    print("🚀 开始AIQuant异步问题诊断")
    print("=" * 80)
    
    results = {}
    
    # 测试1: DataCache cleanup方法
    results['datacache_cleanup'] = test_datacache_cleanup()
    
    # 测试2: get_async_engine导入
    results['get_async_engine_import'] = test_get_async_engine_import()
    
    # 测试3: 事件循环隔离
    results['event_loop_isolation'] = await test_event_loop_isolation()
    
    # 测试4: 简化lifespan测试
    results['simple_lifespan'] = await test_simple_lifespan()
    
    # 测试5: 数据库模块结构
    results['database_module_structure'] = test_database_module_structure()
    
    # 总结
    print("\n" + "=" * 80)
    print("📊 诊断结果总结")
    print("=" * 80)
    
    passed = sum(1 for result in results.values() if result)
    total = len(results)
    
    for test_name, result in results.items():
        status = "✅ 通过" if result else "❌ 失败"
        print(f"  {test_name}: {status}")
    
    print(f"\n📈 诊断成功率: {passed}/{total} ({passed/total*100:.1f}%)")
    
    if passed == total:
        print("🎉 所有诊断测试通过！")
    else:
        print("⚠️ 发现问题，需要修复")
        
    return results

if __name__ == "__main__":
    asyncio.run(main())